package com.github.phoenics.teacher.itheima.netty.first2;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 *  第一个Netty程序 TimeClient
 *
 * @author Phoenics Chow
 * on 2020年01月13日
 */
public class TimeClient {
    /**
     * 使用 3 个线程模拟三个客户端
     *
     * @param args
     */
    public static void main(String[] args) {
        new Thread(new MyThread()).start();
       /* for (int i = 0; i < 3; i++) {
            new Thread(new MyThread()).start();
        }*/
    }

    static class MyThread implements Runnable {

        @Override
        public void run() {
            connect("localhost", 9898);
        }

        public void connect(String host, int port) {
            EventLoopGroup group = new NioEventLoopGroup();
            try {
                Bootstrap b = new Bootstrap();
                b.group(group)
                        .channel(NioSocketChannel.class)
                        .handler(new ChannelInitializer<SocketChannel>() {
                            @Override
                            public void initChannel(SocketChannel ch) throws Exception {
                                //加入新的handler
                                ch.pipeline().addLast(new FirstClientHandler());

                            }
                        });
                ChannelFuture channelFuture = b.connect(host, port).sync();
                System.out.println(Thread.currentThread().getName() + ",客户端发起异步连接..........");
                channelFuture.channel().closeFuture().sync();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                group.shutdownGracefully();
            }
        }
    }
}
